import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { MessageBox, Message } from 'element-ui'

const getDefaultState = () => {
  return {
    account: JSON.parse(sessionStorage.getItem("ACCOUNT_INFO"))||'',
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password ,role:0}).then(res => {
        commit('SET_ACCOUNT', account)
        sessionStorage.setItem("ACCOUNT_INFO", JSON.stringify(account))
        Message({
          message: res.data || '登录成功',
          type: 'success',
          duration: 2 * 1000
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    const  data  = {'name':'admin','avatar':'https://i.postimg.cc/FsVmV7bc/1.jpg'}
    if (!data) {
      return reject('Verification failed, please Login again.')
    }
    const { name, avatar } = data
    commit('SET_NAME', name)
    commit('SET_AVATAR', avatar)
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     const { data } = response
    //
    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }
    //
    //     const { name, avatar } = data
    //
    //     commit('SET_NAME', name)
    //     commit('SET_AVATAR', avatar)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // user logout
  logout({ commit, state }) {
    sessionStorage.removeItem("ACCOUNT_INFO")
    commit('SET_ACCOUNT','')
    resetRouter()
    commit('RESET_STATE')
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  // resetToken({ commit }) {
  //   //  return new Promise(resolve => {
  //   commit('SET_TOKEN','')
  //   removeToken() // must remove  token  first
  //   commit('RESET_STATE')
  //   //  resolve()
  //   //  })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

